package org.darcy.service.privilege.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.darcy.dao.privilege.SysMenuMapper;
import org.darcy.entity.privilege.SysMenu;
import org.darcy.entity.privilege.SysRoleMenu;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.service.privilege.SysMenuService;
import org.darcy.service.privilege.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SysMenuServiceImpl extends GenericServiceImpl<SysMenu> implements SysMenuService {

	@Autowired
	private SysMenuMapper SysMenuMapper;

	@Autowired
	private SysRoleMenuService SysRoleMenuService;

	@Override
	public void save(SysMenu menu) {
		if (menu.getId() != null) {
			this.update(menu);
		} else {
			this.insert(menu);
		}
	}

	@Override
	public void deleteByIds(List<String> ids) {
		if (CollectionUtils.isNotEmpty(ids)) {
			// 1、删除角色菜单
			LambdaQueryWrapper<SysRoleMenu> aclLambdaQueryWrapper = new LambdaQueryWrapper<>();
			aclLambdaQueryWrapper.in(SysRoleMenu::getMenuId, ids);
			SysRoleMenuService.deleteBatch(aclLambdaQueryWrapper);
			// 2、删除菜单
			this.deleteByIds(ids);
		}
	}

	@Override
	public List<SysMenu> getAll(SysMenu menu) {
		LambdaQueryWrapper<SysMenu> moduleLambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(menu.getName())) {
			moduleLambdaQueryWrapper.like(SysMenu::getName, menu.getName()).or().like(SysMenu::getSn, menu.getName());
		}
		moduleLambdaQueryWrapper.eq(SysMenu::getDelFlag, 1).orderByAsc(SysMenu::getOrderNo);
		List<SysMenu> modules = this.getList(moduleLambdaQueryWrapper);

		return modules;
	}

	@Override
	public SysMenu getModuleBySn(String sn) {
		LambdaQueryWrapper<SysMenu> moduleLambdaQueryWrapper = new LambdaQueryWrapper<>();
		moduleLambdaQueryWrapper.eq(SysMenu::getSn, sn);
		return this.getOne(moduleLambdaQueryWrapper);
	}

	@Override
	public List<SysMenu> getMenuList(Integer uid) {
		// 所有uid都小于1000，暂时获取所有菜单
		if (uid == 1) {
			LambdaQueryWrapper<SysMenu> moduleLambdaQueryWrapper = new LambdaQueryWrapper<>();
			moduleLambdaQueryWrapper.orderByAsc(SysMenu::getOrderNo);
			List<SysMenu> list = this.getList(moduleLambdaQueryWrapper);
			return list;
		}
		List<SysMenu> list = SysMenuMapper.getMenuList(uid);
		return list;
	}
}
